<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;

class CustomerInfo extends Model
{
    use HasFactory;

    const RECOMMEND_STATUS_CLUE = 'clue';
    const RECOMMEND_STATUS_DRIVER = 'driver';
    const RECOMMEND_STATUS_BUY_CAR = 'buycar';

    public static $statusMap = [
        self::RECOMMEND_STATUS_CLUE  => '已留资',
        self::RECOMMEND_STATUS_DRIVER => '已试驾',
        self::RECOMMEND_STATUS_BUY_CAR => '已购车',
    ];

    protected $fillable = [
        'user_id', 'name', 'phone', 'vehicle_id', 'activity_id', 'province', 'city', 'dealer_id', 'channel', 'remark'
    ];

    protected $casts = [
        'activity_id' => 'integer',
        'user_id' => 'integer',
        'vehicle_id' => 'integer',
        'dealer_id' => 'integer',
        'referee_id' => 'integer',
        'clue_point' => 'integer',
        'driver_point' => 'integer',
        'buy_car_point' => 'integer',
        'driver_at' => 'datetime',
        'buy_car_at' => 'datetime',
        'remark'    => 'json'
    ];

    public function activity()
    {
        return $this->belongsTo(Activity::class);
    }

    public function dealer()
    {
        return $this->belongsTo(Dealer::class);
    }

    public function vehicle()
    {
        return $this->belongsTo(Vehicle::class);
    }

    public function user()
    {
        return $this->belongsTo(User::class);
    }

    public function userDraw()
    {
        return $this->hasOne(UserDraw::class);
    }

    public function referee()
    {
        return $this->belongsTo(User::class, 'referee_id', 'id');
    }

    public function rmore()
    {
        return $this->belongsTo(Referee::class, 'referee_id', 'user_id');
    }

    public function scopeStatus($query, $status)
    {
        switch ($status) {
            case self::RECOMMEND_STATUS_CLUE:
                return $query->whereNull('driver_at');
                break;
            case self::RECOMMEND_STATUS_DRIVER:
                return $query->whereNotNull('driver_at')->whereNull('buy_car_at');
                break;
            case self::RECOMMEND_STATUS_BUY_CAR:
                return $query->whereNotNull('driver_at')->whereNotNull('buy_car_at');
                break;
            default:
                return $query;
        }
    }

    public function scopeDealerCode($query, $dealer_code)
    {
        $dealer = Dealer::where('code', $dealer_code)->first();
        return $query->where('dealer_id', $dealer->id);
    }

    public function getStatusAttribute()
    {
        if ($this->driver_at) {
            if ($this->buy_car_at) {
                return self::RECOMMEND_STATUS_BUY_CAR;
            } else {
                return self::RECOMMEND_STATUS_DRIVER;
            }
        } else {
            return self::RECOMMEND_STATUS_CLUE;
        }
    }

    public function getStatusChAttribute()
    {
        return self::$statusMap[$this->status];
    }
}
